package com.example.seckill.auth.dao;

import com.example.seckill.auth.entity.Seckill;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author HL
 */
@Component
public class RedisDao {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StringRedisTemplate redisTemplate;

    private Gson gson = new Gson();

    /**
     * 获取Redis
     *
     * @param seckillId
     * @return
     */
    public Seckill getSeckill(long seckillId) {
        Seckill seckill = null;
        try {
            String json = redisTemplate.opsForValue().get(String.valueOf(seckillId));
            if(!StringUtils.isNullOrEmpty(json)){
                seckill = gson.fromJson(json,Seckill.class);
                return seckill;
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return seckill;
    }

    public void putSeckill(Seckill seckill) {
        try {
            System.out.println(seckill.getSeckillId().toString());
            redisTemplate.opsForValue().set(seckill.getSeckillId().toString(), gson.toJson(seckill), 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
